import { Picker, View } from "@tarojs/components"
import classNames from "classnames"
import { useMemo } from "react"
import './index.scss'

interface SelectPickerProps  {
  label: string
  value?: any
  onChange: (value: any) => void
  options: { label: string, value: any }[]
  placeholder?: string
}

const SelectPicker = ({ value, onChange, options, label, placeholder }: SelectPickerProps) => {
  const range = useMemo(() => {
    return options.map(option => option.label)
  }, [options])
  
  const pickerValue = useMemo(() => {
    return options.findIndex(option => option.value === value)
  }, [options, value])

  return (
    <View className='select-picker pv-normal-mh-normal row-between-center'>
      <View className='label text-primary-bold'>{label}</View>
      <View className='flex-1'>
        <Picker
          mode='selector'
          onChange={(e) => {
            const index = Number(e.detail.value)
            index >= 0 && onChange(options[e.detail.value].value)
          }}
          value={pickerValue}
          range={range}
        >
          <View
            className={classNames({
              'text-secondary': !value,
              'text-primary': value,
            })}
          >
            { pickerValue >= 0 ? options[pickerValue].label : placeholder}
          </View>
        </Picker>
      </View>
    </View>
  )
}

export default SelectPicker